package com.wuliu.system.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.wuliu.common.constant.CacheConstants;
import com.wuliu.common.constant.Constants;
import com.wuliu.common.core.redis.RedisCache;
import com.wuliu.common.core.domain.entity.SysAppletUser;
import com.wuliu.common.utils.StringUtils;
import com.wuliu.system.service.AppTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author realue
 * @version 1.0
 * @date 2023-10-08 17:05
 */
@Service
public class AppTokenServiceImpl implements AppTokenService {
    @Resource
    private RedisCache redisCache;

    /**
     * 生成token，缓存用户登录信息 有效期7天
     *
     * @param sysUser
     * @return
     */
    @Override
    public String generateToken(SysAppletUser sysUser) {
        String token = IdUtil.randomUUID();
        redisCache.setCacheObject(CacheConstants.TOKEN_SYS_USER_LOGIN_INFO_KEY + token, JSONUtil.toJsonStr(sysUser), Constants.APP_TOKEN_EXPIRE_TIME, TimeUnit.DAYS);
        return token;
    }

    /**
     * 校验证短信验证码
     *
     * @param userNo
     * @param code
     * @return
     */
    @Override
    public Boolean checkVerificationCode(String userNo, String code) {
        String redisCode = redisCache.getCacheObject(CacheConstants.LOGIN_VERIFICATION_CODE_KEY + userNo);
        if (StringUtils.isEmpty(redisCode)) {
            return false;
        }
        if (code.equals(redisCode)) {
            redisCache.deleteObject(CacheConstants.LOGIN_VERIFICATION_CODE_KEY + userNo);
            return true;
        }
        return false;
    }

    /**
     * 缓存短信验证码 有效期 2 分钟
     *
     * @param userNo
     * @param code
     */
    @Override
    public void saveVerificationCode(String userNo, String code) {
        redisCache.setCacheObject(CacheConstants.LOGIN_VERIFICATION_CODE_KEY + userNo, code, 2, TimeUnit.MINUTES);
    }
}
